package org.note.law.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.domain.ResponseDTO;
import org.lboot.jpa.utils.JpaDataUtil;
import org.note.law.module.provision.LawProvision;
import org.note.law.module.provision.LawProvisionService;
import org.note.law.module.provision.params.LawProvisionQueryParams;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("law")
@Api(tags = "法条管理")
@AllArgsConstructor
public class LawProvisionController {
    LawProvisionService service;

    @SneakyThrows
    @GetMapping("provisions")
    @ApiOperation(value = "法条查询")
    public ResponseDTO<Object> dataQuery(LawProvisionQueryParams params){

        Pageable pageable = JpaDataUtil.buildPageable(params);
        LawProvision provision = new LawProvision();
        // 获取检索关键词， 存在关键词就以关键词为先
        String searchKey = params.getSearchKey();
        if (Validator.isEmpty(searchKey)){
            BeanUtil.copyProperties(params, provision);
            Example<LawProvision> example = Example.of(provision);
            return ResponseDTO.succData(
                    service.getAll(pageable, example)
            );
        }
        else {
            Specification<LawProvision> spec = (root, query, cb) -> {
                // 构建谓词查询
                Predicate matchTitle = cb.like(root.get("title"), "%" + searchKey + "%");
                Predicate matchContent = cb.like(root.get("content"), "%" + searchKey + "%");
                Predicate matchCodeName = cb.equal(root.get("codeName"), searchKey);
                return cb.or(matchTitle, matchContent, matchCodeName);
            };
            return ResponseDTO.succData(
                    service.getAll(pageable, spec)
            );
        }
    }
}
